<?php

namespace app\admin\controller\parts;

use Throwable;
use app\common\controller\Backend;
use app\common\controller\Approval;
use think\App;
use think\facade\Db;

/**
 * 配件入库管理
 */
class Entry extends Backend
{
    /**
     * Entry模型对象
     * @var object
     * @phpstan-var \app\admin\model\parts\Entry
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array $withJoinTable = ['partsInfo','manufacturerInfo'];

    protected string|array $quickSearchField = ['parts_info_id', 'id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\parts\Entry;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $res->visible(['partsInfo' => ['parts_name','parts_code','manufacturer_info_id','parts_img'],'manufacturerInfo'=>['manufacturer_name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $alias = ["ba_parts_entry"];
        $row = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where('Entry.id',$id)
            ->find();
        $row->visible(['partsInfo' => ['parts_name','parts_code','manufacturer_info_id','parts_img'],'manufacturerInfo'=>['manufacturer_name']]);

        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            // 数据编辑需要审核通过才执行。
            $data = $this->request->post();
            $OldJson = json_encode($row);
            $NewJson = json_encode($data);
            $data['is_approval'] = 1;
            $row->save($data);
            // 提交记录
            $Approval = new Approval();
            $res = $Approval->AddApprovalRecord($OldJson,$NewJson,2,$data["approval"],$this->auth->id);
            if($res){
                $this->success("提交成功");
            }else{
                $this->error("提交失败");
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                //配件入库逻辑
                $this->model->PartsEntry($data);
                //提交事务
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
/**
     * 删除
     * @param array $ids
     * @throws Throwable
     */
    public function del(array $ids = []): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }
        //删除审核
        $id = $ids[0];
        $alias = ["ba_parts_entry"];
        $row = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where('Entry.id',$id)
            ->find();
        $OldJson = json_encode($row);
        $NewJson = json_encode("");

        $data['is_approval'] = 1;
        $row->save($data);
        // 提交记录

        $Approval = new Approval();
        $res = $Approval->AddApprovalRecord($OldJson,$NewJson,3,$ids[1],$this->auth->id);
        if ($res) {
            $this->success("提交成功");
        } else {
            $this->error(__('The data is waiting for approval'));
        }
    }
    /**
     * 删除
     * @param int $id
     * @throws Throwable
     */
    public function GetInfo(int $id = null): void
    {
        //删除审核
        $where = "";
        if($id != null)
        {
            $where = "and manufacturerInfo.id = ".$id;
        }
        $sql = "SELECT
                    manufacturerInfo.id,
                    max(manufacturerInfo.manufacturer_name) as Name,
                    sum( entry.parts_cost )  as Money
                FROM
                    ba_parts_entry entry
                    LEFT JOIN ba_parts_info partsInfo ON entry.parts_info_id = partsInfo.id
                    LEFT JOIN ba_manufacturer_info manufacturerInfo ON partsInfo.manufacturer_info_id = manufacturerInfo.id 
                WHERE
                    manufacturerInfo.status = 1 ".$where."
                GROUP BY
                    manufacturerInfo.id";
        $result = Db::query($sql);

        $this->success('', [
            'list'   => $result,
            'total'  => count($result),
            'remark' => get_route_remark(),
            'sql' => $sql,
        ]);

//        if ($res) {
//            $this->success("提交成功");
//        } else {
//            $this->error(__('The data is waiting for approval'));
//        }
    }
    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}
